import json
from urllib import urlopen, urlencode
from django.http import HttpResponse
from django.conf import settings

#import cache
import util

API_RULESET = {
    'price_': {
        'cond': {
            'new':  (False, lambda i: i['condition'] == 'new'),
            'used': (False, lambda i: i['condition'] == 'used')
        },
        'cnvt': lambda i: '%.2f' % i['inventories'][0]['price']
    },
    'title': {
        'cond': None,
        'cnvt': lambda i: i['title']
    },
    'isbn_13': {
        'cond': [lambda i: 'gtin' in i, lambda i: util.valid_isbn_13(i['gtin'][1:])],
        'cnvt': lambda i: i['gtin'][1:]
    },
    'isbn_10': {
        'cond': [lambda i: 'gtin' in i, lambda i: util.valid_isbn_13(i['gtin'][1:])],
        'cnvt': lambda i: '%s%s' % (i['gtin'][4:-1], str(11 - sum(map(lambda a,b: a * b, range(10,1,-1), [int(i) for i in list(i['gtin'][4:])][:-1])) % 11).replace('10','X'))
    },
    'image_url': {
        'cond': lambda i: 'images' in i,
        'cnvt': lambda i: i['images'][0]['link']
    },
    'purchase_url': {
        'cond': None,
        'cnvt': lambda i: i['link']
    },
    'description': {
        'cond': None,
        'cnvt': lambda i: i['description']
    }
}

def products_api(args):
    # The initial requst structure
    base = 'https://www.googleapis.com/shopping/search/v1/public/products'
    attr = {
        #'key': 'AIzaSyD5bSzuKaORO1CKORYhJJcsSLrEOiEtJDI',
	'key': 'AIzaSyDB00if3zMjkwxIErvmhDz11iWKrWogRNY',
        'country': 'US',
        'spelling.enabled': 'true',
        'restrictBy': {}
    }

    # Handle when no request is made (no getvars)
    if len(args) == 0: raise Exception('No arguments')

    # Process provided arguments
    for key, val in args.items():
        if key == 'q': attr[str(key)] = val
        else: attr['restrictBy'][str(key)] = val

    # Perform the product search
    if len(attr['restrictBy']) == 0: del attr['restrictBy']
    else: attr['restrictBy'] = ','.join(['%s=%s' % (key, val) for key, val in attr['restrictBy'].items()])
    base = '%s?%s' % (base, urlencode(attr.items()))
    try:
        data = json.load(urlopen(base))
    except: raise Exception('Unable to process request')

    # Handle any errors with loading the data
    if data == 'error' or 'items' not in data:
        raise Exception('No data returned in request')

    # Convert the data into the standard format
    items = []
    for item in data['items']:
        items.append({'type': 'book', 'attributes': util.convert(item['product'], API_RULESET)})

    return items

def search(request):
    # Extract optional arguments
    try:
        args = dict(request.GET.items())
        opts = {'indent': None, 'max': 0, 'offset': 0}
        for o in ['indent', 'max', 'offset']:
            if o in args:
                opts[o] = int(args[o])
                del args[o]

        # Search for the requested items
	items = products_api(args)

        # Format and return the response
        if opts['max'] == 0: opts['max'] = len(items)
        return HttpResponse(json.dumps(items[opts['offset']:(opts['max']+opts['offset'])], 
        indent = opts['indent']), mimetype = 'application/json')
    except: return util.error(0)
